package com.yami.shop.im.socket;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.shop.bean.model.ImMsgBizSkills;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Json;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.im.bean.ImMsgBizUserHistory;
import com.yami.shop.im.constants.Constant;
import com.yami.shop.im.constants.MsgCode;
import com.yami.shop.im.constants.SendType;
import com.yami.shop.im.hanlder.SecurityHandler;
import com.yami.shop.im.param.MessageInfo;
import com.yami.shop.im.service.ImMsgBizUserHistoryService;
import com.yami.shop.im.vo.MsgItem;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.multishop.model.YamiShopUser;
import com.yami.shop.security.platform.model.YamiSysUser;
import com.yami.shop.service.ImMsgBizSkillsService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.UserService;
import com.yami.shop.sys.common.model.SysUser;
import com.yami.shop.sys.common.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 用户收到的消息
 * 10,"无法获取用户信息"
 * 11,"账户已在别处登录，请刷新"
 * 12,"对方不在线"
 * 13, "内容格式有误"
 *
 * @author Lzk
 */
@ServerEndpoint("/im/websocket/user/{token}/{userId}")
@Component
@Slf4j
public class UserWebSocketServer {

    /**
     * UUID为key
     */
    public static final ConcurrentHashMap<String, Session> USER_MAP = new ConcurrentHashMap<>(256);

    private static SecurityHandler securityHandler;

    private static UserService userService;

    private static ShopDetailService shopDetailService;

    private static SysUserService sysUserService;

    private static ImMsgBizUserHistoryService imMsgBizUserHistoryService;

    private static ImMsgBizSkillsService imMsgBizSkillsService;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        securityHandler = applicationContext.getBean(SecurityHandler.class);
        userService = applicationContext.getBean(UserService.class);
        shopDetailService = applicationContext.getBean(ShopDetailService.class);
        sysUserService = applicationContext.getBean(SysUserService.class);
        imMsgBizUserHistoryService = applicationContext.getBean(ImMsgBizUserHistoryService.class);
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        log.info("创建连接");
        YamiUser yamiUser = securityHandler.getUser(token);
        if (yamiUser == null) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CAN_NOT_FIND_USER_INFO, "无法获取用户信息")));
            }
            return;
        }

        // 如果原来就有token
        Session oldSession = USER_MAP.get(Constant.USER_PREFIX + yamiUser.getUserId());
        if (oldSession != null) {
            // 客户端收到301，关闭ws链接，弹出提示
            if (oldSession.isOpen()) {
                oldSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.LOGIN_IN_OTHER_PLACE, "账户已在别处登录，请刷新")));
                oldSession.close();
            }
        }

        USER_MAP.put(Constant.USER_PREFIX + yamiUser.getUserId(), session);
        RedisUtil.set(Constant.USER_PREFIX + yamiUser.getUserId(), "", 0);
        if (session.isOpen()) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success()));
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("token") String token, @PathParam( "userId") String userId) throws IOException {
        log.info("关闭连接");
        USER_MAP.remove(Constant.USER_PREFIX + userId);
        RedisUtil.del(Constant.USER_PREFIX + userId);
    }

    /**
     * 连接错误调用的方法
     */
    @OnError
    public void onError(Session session, @PathParam("token") String token, Throwable error, @PathParam( "userId") String userId) throws IOException {
        log.error("发生错误");
        error.printStackTrace();
        USER_MAP.remove(Constant.USER_PREFIX + userId);
        RedisUtil.del(Constant.USER_PREFIX + userId);
    }

    /**
     * 收到客户端消息后调用的方法，该消息由用户发过来
     *
     * @param sourceMessage 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String sourceMessage, @PathParam("token") String token, Session session) throws IOException {
        YamiUser yamiUser = securityHandler.getUser(token);
        if (Objects.isNull(yamiUser)) {
            log.error("无法获取用户信息");
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CAN_NOT_FIND_USER_INFO, "无法获取用户信息")));
            }
            return;
        }

        if (StrUtil.isBlank(sourceMessage)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CONTENT_FORMAT_ERROR, "内容格式有误")));
            }
            return;
        }

        log.info("sourceMessage: " + sourceMessage);

        MessageInfo messageInfo = Json.parseObject(sourceMessage, MessageInfo.class);

        if (Objects.isNull(messageInfo)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CONTENT_FORMAT_ERROR, "内容格式有误")));
            }
            return;
        }

        // 保持心跳
        if (StrUtil.equals(messageInfo.getContent(), Constant.HEART_BEAT)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.HEART_BEAT, "保持心跳")));
            }
            return;
        }

        Long bizId = Long.valueOf(messageInfo.getToId());
        String userId = yamiUser.getUserId();
        User user = userService.getUserByUserId(yamiUser.getUserId());

        // 判断用户是发送给商家客服还是平台客服
        switch (messageInfo.getSendType()) {
            case SendType.PLATFORM:
                sendToPlatform(bizId, session, messageInfo, userId, user);
                break;
            case SendType.SHOP:
                sendToShop(bizId, session, messageInfo, userId, user);
                break;
            default:
                break;
        }
    }

    public void sendToPlatform(Long bizId, Session session, MessageInfo messageInfo, String userId, User user) throws IOException {
        SysUser sysUser = sysUserService.getSysUserById(bizId);

        if (Objects.isNull(sysUser)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.PARAM_ERROR, "参数有误")));
            }
            return;
        }

        // 获取消息历史
        if (Objects.nonNull(messageInfo.getHistory()) && Objects.equals(messageInfo.getHistory(), true)) {
            Page<MsgItem> msgItemPage = imMsgBizUserHistoryService.getUserPlatformHistory(sysUser, messageInfo, bizId, userId, user);
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.HISTORY, msgItemPage)));
            }
            return;
        }

        // 标记消息已读
        if (Objects.nonNull(messageInfo.getRead()) && Objects.equals(messageInfo.getRead(), true)) {
            if (Objects.nonNull(messageInfo.getMsgIds()) && !messageInfo.getMsgIds().isEmpty()) {
                List<ImMsgBizUserHistory> imMsgBizUserHistories = imMsgBizUserHistoryService.markUserPlatformRead(messageInfo, bizId, userId);
                if (!imMsgBizUserHistories.isEmpty()) {
                    if (session.isOpen()) {
                        session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success()));
                    }
                    if (Objects.nonNull(messageInfo.getReadNoticePlatformUserId())) {
                        Session sysSession = PlatformWebSocketServer.SYS_MAP.get(Constant.SYS_PREFIX + messageInfo.getReadNoticePlatformUserId());
                        if (Objects.nonNull(sysSession)) {
                            if (sysSession.isOpen()) {
                                sysSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.READ, messageInfo.getMsgIds())));
                            }
                        }
                    } else {
                        Long sysUserId = RedisUtil.getLongValue(Constant.IN_CHARGE_SYS + userId);
                        if (Objects.nonNull(sysUserId)) {
                            Session sysSession = PlatformWebSocketServer.SYS_MAP.get(Constant.SYS_PREFIX + sysUserId);
                            if (Objects.nonNull(sysSession)) {
                                if (sysSession.isOpen()) {
                                    sysSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.READ, messageInfo.getMsgIds())));
                                }
                            }
                        }
                    }
                }
            }
            return;
        }

        if (Objects.nonNull(messageInfo.getOnlineOrOffline()) && Objects.equals(messageInfo.getOnlineOrOffline(), true)) {
            Set<String> set = RedisUtil.keys(Constant.ONLINE_SYS_PREFIX + "*");
            MsgItem msgItem = new MsgItem();
            msgItem.setChatType(SendType.PLATFORM);
            msgItem.setShopId(bizId);
            if (!set.isEmpty()) {
                msgItem.setOnlineOrOffline(true);
            } else {
                msgItem.setOnlineOrOffline(false);
            }
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.ONLINE_OR_OFFLINE, msgItem)));
            }
        }

        // 发送消息
        if (Objects.nonNull(messageInfo.getContent()) && !messageInfo.getContent().isEmpty()) {
            platformSendMessage(bizId, messageInfo, userId, user, sysUser);
        }
    }

    private void platformSendMessage(Long bizId, MessageInfo messageInfo, String userId, User user, SysUser sysUser) throws IOException {
        // 查出负责该客户的客服
        if (Objects.nonNull(RedisUtil.getLongValue(Constant.IN_CHARGE_SYS + userId))) {
            Long sysUserId = RedisUtil.getLongValue(Constant.IN_CHARGE_SYS + userId);
            Session sysSession = PlatformWebSocketServer.SYS_MAP.get(Constant.SYS_PREFIX + sysUserId);
            if (Objects.nonNull(sysSession)) {
                ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.saveUserPlatformHistory(messageInfo, sysUserId, userId);
                // 发送消息给平台
                MsgItem msgItem = imMsgBizUserHistoryService.getUserPlatformMsgItem(sysUser, user, imMsgBizUserHistory);
                if (sysSession.isOpen()) {
                    sysSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
                    messagePla(messageInfo, user, sysUser, sysUserId, sysSession);
                }
                return;
            }
            RedisUtil.del(Constant.IN_CHARGE_SYS + userId);
        }
        // 如果没有跟进的客服或者跟进的客服不在线
        Set<String> set = RedisUtil.keys(Constant.SYS_PREFIX + "*");
        List<String> listSysUser = new ArrayList<>();
        for (String key : set) {
            if (key.startsWith(Constant.SYS_PREFIX)) {
                listSysUser.add(key);
            }
        }
        if (!listSysUser.isEmpty()) {
            // 随机选一个在线客服
            int index = (int) (Math.random() * listSysUser.size());
            long tempLength = (Constant.SYS_PREFIX).length();
            Long sysUserId = Long.valueOf(listSysUser.get(index).substring((int) tempLength));
            Session sysSession = PlatformWebSocketServer.SYS_MAP.get(Constant.SYS_PREFIX + sysUserId);
            RedisUtil.set(Constant.IN_CHARGE_SYS + userId, sysUserId, 0);
            ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.saveUserPlatformHistory(messageInfo, sysUserId, userId);
            // 发送消息给平台
            MsgItem msgItem = imMsgBizUserHistoryService.getUserPlatformMsgItem(sysUser, user, imMsgBizUserHistory);
            if (Objects.nonNull(sysSession)) {
                if (sysSession.isOpen()) {
                    sysSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
                }
            }
            Set<String> set2 = RedisUtil.keys(Constant.ONLINE_SYS_PREFIX + sysUserId + Constant.UNDERLINE + "*");
            List<Session> listSysUser2 = new ArrayList<>();
            for (String key : set2) {
                if (key.startsWith(Constant.ONLINE_SYS_PREFIX + sysUserId + Constant.UNDERLINE)) {
                    listSysUser2.add(PlatformOnlineWebSocketServer.SYS_ONLINE_MAP.get(key));
                }
            }
            if (!listSysUser2.isEmpty()) {
                RedisUtil.set(Constant.UNREAD_SYS_PREFIX + sysUserId + Constant.UNDERLINE, 1, 0);
                MsgItem msgItem3 = new MsgItem();
                msgItem3.setNewMessage(true);
                for (Session sysSession2 : listSysUser2) {
                    if (Objects.nonNull(sysSession2)) {
                        if (sysSession2.isOpen()) {
                            sysSession2.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem3)));
                        }
                    }
                }
            }
        } else {
            ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.saveUserPlatformHistory(messageInfo, bizId, userId);
            Set<String> set2 = RedisUtil.keys(Constant.ONLINE_SYS_PREFIX + "*");
            List<Session> listSysUser2 = new ArrayList<>();
            for (String key : set2) {
                if (key.startsWith(Constant.ONLINE_SYS_PREFIX)) {
                    listSysUser2.add(PlatformOnlineWebSocketServer.SYS_ONLINE_MAP.get(key));
                }
            }
            if (!listSysUser2.isEmpty()) {
                RedisUtil.set(Constant.UNREAD_SYS_PREFIX + bizId + Constant.UNDERLINE, 1, 0);
                MsgItem msgItem = new MsgItem();
                msgItem.setNewMessage(true);
                for (Session sysSession2 : listSysUser2) {
                    if (Objects.nonNull(sysSession2)) {
                        if (sysSession2.isOpen()) {
                            sysSession2.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
                        }
                    }
                }
            }
        }
        messagePla(messageInfo, user, sysUser, sysUser.getUserId(), null);
    }

    public void sendToShop(Long bizId, Session session, MessageInfo messageInfo, String userId, User user) throws IOException {
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(bizId);

        if (Objects.isNull(shopDetail)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.PARAM_ERROR, "参数有误")));
            }
            return;
        }

        // 获取消息历史
        if (Objects.nonNull(messageInfo.getHistory()) && Objects.equals(messageInfo.getHistory(), true)) {
            Page<MsgItem> msgItemPage = imMsgBizUserHistoryService.getUserShopHistory(shopDetail, messageInfo, bizId, userId, user);
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.HISTORY, msgItemPage)));
            }
            return;
        }

        // 标记消息已读
        if (Objects.nonNull(messageInfo.getRead()) && Objects.equals(messageInfo.getRead(), true)) {
            if (Objects.nonNull(messageInfo.getMsgIds()) && !messageInfo.getMsgIds().isEmpty()) {
                List<ImMsgBizUserHistory> imMsgBizUserHistories = imMsgBizUserHistoryService.markUserShopRead(messageInfo, bizId, userId);
                if (!imMsgBizUserHistories.isEmpty()) {
                    if (session.isOpen()) {
                        session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success()));
                    }
                    if (Objects.nonNull(messageInfo.getReadNoticeEmployeeId())) {
                        Session shopSession = ShopWebSocketServer.SHOP_EMPLOYEE_MAP.get(Constant.SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE + messageInfo.getReadNoticeEmployeeId());
                        if (Objects.nonNull(shopSession)) {
                            if (shopSession.isOpen()) {
                                shopSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.READ, messageInfo.getMsgIds())));
                            }
                        }
                    } else {
                        Long employeeId = RedisUtil.getLongValue(Constant.IN_CHARGE_SHOP + bizId + Constant.UNDERLINE + userId);
                        if (Objects.nonNull(employeeId)) {
                            Session shopSession = ShopWebSocketServer.SHOP_EMPLOYEE_MAP.get(Constant.SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE + employeeId);
                            if (Objects.nonNull(shopSession)) {
                                if (shopSession.isOpen()) {
                                    shopSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.READ, messageInfo.getMsgIds())));
                                }
                            }
                        }
                    }
                }
            }
            return;
        }

        if (Objects.nonNull(messageInfo.getOnlineOrOffline()) && Objects.equals(messageInfo.getOnlineOrOffline(), true)) {
            Set<String> set = RedisUtil.keys(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE + "*");
            MsgItem msgItem = new MsgItem();
            msgItem.setChatType(SendType.SHOP);
            msgItem.setShopId(bizId);
            if (!set.isEmpty()) {
                msgItem.setOnlineOrOffline(true);
            } else {
                msgItem.setOnlineOrOffline(false);
            }
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.ONLINE_OR_OFFLINE, msgItem)));
            }
        }

        // 发送消息
        if (Objects.nonNull(messageInfo.getContent()) && !messageInfo.getContent().isEmpty()) {
            shopSendMessage(bizId, messageInfo, userId, user, shopDetail);
        }
    }

    private void shopSendMessage(Long bizId, MessageInfo messageInfo, String userId, User user, ShopDetail shopDetail) throws IOException {
        // 查出负责该客户的客服
        if (Objects.nonNull(RedisUtil.getLongValue(Constant.IN_CHARGE_SHOP + bizId + Constant.UNDERLINE + userId))) {
            Long employeeId = RedisUtil.getLongValue(Constant.IN_CHARGE_SHOP + bizId + Constant.UNDERLINE + userId);
            Session shopSession = ShopWebSocketServer.SHOP_EMPLOYEE_MAP.get(Constant.SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE + employeeId);
            if (Objects.nonNull(shopSession)) {
                ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.saveUserShopHistory(messageInfo, bizId, userId, employeeId, 1);
                // 发送消息给客服
                MsgItem msgItem = imMsgBizUserHistoryService.getUserShopMsgItem(shopDetail, user, imMsgBizUserHistory);
                if (shopSession.isOpen()) {
                    shopSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
                    messageMul(bizId, messageInfo, userId, user,shopDetail, employeeId, shopSession);
                }
                return;
            }
            RedisUtil.del(Constant.IN_CHARGE_SHOP + bizId + Constant.UNDERLINE + userId);
        }
        // 如果没有跟进的客服或者跟进的客服不在线
        Set<String> set = RedisUtil.keys(Constant.SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE + "*");
        List<String> listEmployee = new ArrayList<>();
        for (String key : set) {
            if (key.startsWith(Constant.SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE)) {
                listEmployee.add(key);
            }
        }
        if (!listEmployee.isEmpty()) {
            // 随机选一个在线客服
            int index = (int) (Math.random() * listEmployee.size());
            long tempLength = (Constant.SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE).length();
            Long employeeId = Long.valueOf(listEmployee.get(index).substring((int) tempLength));
            Session shopSession = ShopWebSocketServer.SHOP_EMPLOYEE_MAP.get(Constant.SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE + employeeId);
            RedisUtil.set(Constant.IN_CHARGE_SHOP + bizId + Constant.UNDERLINE + userId, employeeId, 0);
            ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.saveUserShopHistory(messageInfo, bizId, userId, employeeId,1);
            // 发送消息给客服
            MsgItem msgItem = imMsgBizUserHistoryService.getUserShopMsgItem(shopDetail, user, imMsgBizUserHistory);
            if (Objects.nonNull(shopSession)) {
                if (shopSession.isOpen()) {
                    shopSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
                }
            }
            Set<String> set2 = RedisUtil.keys(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE + employeeId + Constant.UNDERLINE + "*");
            List<Session> listEmployee2 = new ArrayList<>();
            for (String key : set2) {
                if (key.startsWith(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE + employeeId + Constant.UNDERLINE)) {
                    listEmployee2.add(ShopOnlineWebSocketServer.SHOP_ONLINE_EMPLOYEE_MAP.get(key));
                }
            }
            if (!listEmployee2.isEmpty()) {
                MsgItem msgItem3 = new MsgItem();
                msgItem3.setNewMessage(true);
                for (Session shopSession2 : listEmployee2) {
                    if (Objects.nonNull(shopSession2)) {
                        if (shopSession2.isOpen()) {
                            shopSession2.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem3)));
                        }
                    }
                }
            }
        } else {
            ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.saveUserShopHistory(messageInfo, bizId, userId, bizId,0);
            Set<String> set2 = RedisUtil.keys(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE + "*");
            List<Session> listEmployee2 = new ArrayList<>();
            for (String key : set2) {
                if (key.startsWith(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + bizId + Constant.UNDERLINE)) {
                    listEmployee2.add(ShopOnlineWebSocketServer.SHOP_ONLINE_EMPLOYEE_MAP.get(key));
                }
            }
            if (!listEmployee2.isEmpty()) {
                MsgItem msgItem = new MsgItem();
                msgItem.setNewMessage(true);
                for (Session shopSession2 : listEmployee2) {
                    if (Objects.nonNull(shopSession2)) {
                        if (shopSession2.isOpen()) {
                            shopSession2.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
                        }
                    }
                }
            }
        }
        messageMul(bizId, messageInfo, userId, user,shopDetail, Long.parseLong(shopDetail.getUserId()), null);
    }

    private void messageMul(Long bizId, MessageInfo messageInfo, String userId, User user, ShopDetail shopDetail, Long employeeId, Session shopSession ) throws IOException {
        String content = messageInfo.getContent();
        if(content != null && !content.contains("{") && !content.contains("}") && !content.contains(".im")
                && !content.contains(".jpg") && !content.contains(".png") && !content.contains(".gif")) {
            List<ImMsgBizSkills> imMsgBizSkills = imMsgBizSkillsService.list(new LambdaQueryWrapper<ImMsgBizSkills>()
                    .eq(ImMsgBizSkills::getShopId, shopDetail.getShopId())
                    .eq(ImMsgBizSkills::getStatus, 1));
            if(Objects.nonNull(imMsgBizSkills) && imMsgBizSkills.size() != 0){
                Map<String, String> collect = imMsgBizSkills.stream().collect(Collectors.toMap(ImMsgBizSkills::getKeywords, ImMsgBizSkills::getContent));
                StringBuilder collects = new StringBuilder();
                for (Map.Entry<String, String> entry : collect.entrySet()) {
                    if(content.contains(entry.getKey())){
                        collects.append(entry.getValue()).append("\n");
                    }
                };
                if(!collects.toString().equals("")){
                    collects = new StringBuilder(collects.substring(0, collects.length() - 1));
                    MessageInfo msg = new MessageInfo();
                    msg.setMsgType(0);
                    msg.setToId(user.getUserId());
                    msg.setContent(collects.toString());
                    YamiShopUser shopUser = new YamiShopUser();
                    shopUser.setUserId(userId);
                    shopUser.setShopId(bizId);
                    shopUser.setEnabled(true);
                    shopUser.setEmployeeId(employeeId);
                    ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.saveShopUserHistory(msg, shopUser);
                    MsgItem msgItem = imMsgBizUserHistoryService.getUserShopMsgItem(shopDetail, user, imMsgBizUserHistory);
                    Session userSession = UserWebSocketServer.USER_MAP.get(Constant.USER_PREFIX + msg.getToId());
                    if (userSession.isOpen()) {
                        userSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
                    }
                    if(shopSession != null){
                        shopSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
                    }
                }
            }
        }
    }

    private void messagePla(MessageInfo messageInfo, User user, SysUser sysUser, Long employeeId, Session sysSession) throws IOException {
        String content = messageInfo.getContent();
        if(content != null && !content.contains("{") && !content.contains("}") && !content.contains(".im")
                && !content.contains(".jpg") && !content.contains(".png") && !content.contains(".gif")) {
            List<ImMsgBizSkills> imMsgBizSkills = imMsgBizSkillsService.list(new LambdaQueryWrapper<ImMsgBizSkills>()
                    .eq(ImMsgBizSkills::getShopId, com.yami.shop.common.config.Constant.PLATFORM_SHOP_ID)
                    .eq(ImMsgBizSkills::getStatus, 1));
            if(Objects.nonNull(imMsgBizSkills) && imMsgBizSkills.size() != 0){
                Map<String, String> collect = imMsgBizSkills.stream().collect(Collectors.toMap(ImMsgBizSkills::getKeywords, ImMsgBizSkills::getContent));
                StringBuilder collects = new StringBuilder();
                for (Map.Entry<String, String> entry : collect.entrySet()) {
                    if(content.contains(entry.getKey())){
                        collects.append(entry.getValue()).append("\n");
                    }
                };
                if(!collects.toString().equals("")){
                    collects = new StringBuilder(collects.substring(0, collects.length() - 1));
                    MessageInfo msg = new MessageInfo();
                    msg.setMsgType(0);
                    msg.setToId(user.getUserId());
                    msg.setContent(collects.toString());
                    YamiSysUser shopUser = new YamiSysUser();
                    shopUser.setUserId(sysUser.getUserId());
                    shopUser.setEnabled(true);
                    shopUser.setUsername(user.getUserName());
                    shopUser.setEmployeeId(employeeId);
                    ImMsgBizUserHistory imMsgBizUserHistory =  imMsgBizUserHistoryService.savePlatformUserHistory(msg, shopUser);

                    MsgItem msgItem = imMsgBizUserHistoryService.getUserPlatformMsgItem(sysUser, user, imMsgBizUserHistory);
                    Session userSession = UserWebSocketServer.USER_MAP.get(Constant.USER_PREFIX + msg.getToId());
                    if (userSession.isOpen()) {
                        userSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
                    }
                    if (sysSession != null){
                        sysSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
                    }
                }
            }
        }
    }
}
